# ################################################################# #
#### LOAD LIBRARY AND DEFINE CORE SETTINGS                       ####
# ################################################################# #

### Clear memory
rm(list = ls())

### Load Apollo library
library(apollo)

### Set working directory (only works in RStudio)
apollo_setWorkDir()

### Initialise code
apollo_initialise()

### Set core controls
apollo_control = list(
  modelDescr      = "Extended MDC with complementarity and substitution, with observed budget and socio-demographics",
  indivID         = "indivID",
  outputDirectory = "output"
)

# ################################################################# #
#### LOAD DATA AND APPLY ANY TRANSFORMATIONS                     ####
# ################################################################# #

### Load data from within the Apollo package
database = apollo_timeUseData

### Create consumption variables for combined activities
# outside good: time spent at home and travelling
database$t_outside = rowSums(database[,c("t_a01", "t_a06", "t_a10", "t_a11", "t_a12")]) 
database$t_leisure = rowSums(database[,c("t_a07", "t_a08", "t_a09")])

### Randomly split dataset into estimation (70%) and validation (30%)
set.seed(1)
database$validation = runif(nrow(database))>0.7
dbVal    = database[ database$validation,] # validation sample
database = database[!database$validation,] # estimation sample

# ################################################################# #
#### DEFINE MODEL PARAMETERS                                     ####
# ################################################################# #

### Parameters starting values c(name1=value1, name2=value2, ...)
apollo_beta = c(aFemale=-0.005, sigma = 2, 
                # Satiation
                gWork    = 10.425, 
                gSchool  = 9.955, 
                gShopping= 2.065, 
                gPrivate = 4.419, 
                gLeisure = 6.927, 
                # Base utility
                bWork     =-3.372, bSchool   =-5.250, 
                bShopping =-3.663, bPrivate  =-3.973, 
                bLeisure  =-3.300, bWork_FT  = 0.708, 
                bWork_wknd=-1.600, bSchool_young= 0.948, 
                bLeisure_wknd= 0.155, 
                # Compl/subst
                dWorkScho=-0.008, dWorkShop= 0.000, 
                dWorkPriv= 0.000, dWorkLeis= 0.000, 
                dSchoShop= 0.000, dSchoPriv= 0.000, 
                dSchoLeis= 0.000, dShopPriv= 0.010, 
                dShopLeis= 0.012, dPrivLeis= 0.012)

### Names of fixed parameters
apollo_fixed = c('dWorkShop', 'dWorkPriv', 'dSchoShop', 
                 'dSchoPriv', 'dSchoLeis', 'dWorkLeis')

# ################################################################# #
#### GROUP AND VALIDATE INPUTS                                   ####
# ################################################################# #

apollo_inputs = apollo_validateInputs()

# ################################################################# #
#### DEFINE MODEL AND LIKELIHOOD FUNCTION                        ####
# ################################################################# #

apollo_probabilities=function(apollo_beta, apollo_inputs, 
                              functionality="estimate"){
    
  ### Initialise
  apollo_attach(apollo_beta, apollo_inputs)
  on.exit(apollo_detach(apollo_beta, apollo_inputs))
  P = list()
  
  ### Prepare Inputs
  alts  = c("work", "school", "shopping", "private", "leisure")
  nAlt = length(alts)
  ones = setNames(as.list(rep(1, nAlt)), alts)
  continuousChoice = list(work     =     t_a02/60,
                          school   =     t_a03/60,
                          shopping =     t_a04/60,
                          private  =     t_a05/60,
                          leisure  = t_leisure/60)
  utilities = list(
    work     = bWork     + bWork_FT*occ_full_time + bWork_wknd*weekend,
    school   = bSchool   + bSchool_young*(age<=30), 
    shopping = bShopping, 
    private  = bPrivate, 
    leisure  = bLeisure  + bLeisure_wknd*weekend
  )
  gamma = list(work     = gWork,    
               school   = gSchool,
               shopping = gShopping,
               private  = gPrivate,
               leisure  = gLeisure)
  delta = c(0,                 0,         0,         0, 0,
             dWorkScho,         0,         0,         0, 0,
             dWorkShop, dSchoShop,         0,         0, 0,
             dWorkPriv, dSchoPriv, dShopPriv,         0, 0,
             dWorkLeis, dSchoLeis, dShopLeis, dPrivLeis, 0)
  delta = matrix(delta, nrow=nAlt, ncol=nAlt, byrow=TRUE)
  emdc_settings = list(continuousChoice = continuousChoice, 
                        avail            = ones,
                        utilityOutside   = aFemale*female, 
                        utilities        = utilities, 
                        budget           = 24,
                        sigma            = sigma, 
                        gamma            = gamma, 
                        delta            = delta, 
                        cost             = ones)
  P[["model"]] = apollo_emdc(emdc_settings, functionality)
  
  ### Comment out as necessary
  P = apollo_panelProd(P, apollo_inputs, functionality)
  P = apollo_prepareProb(P, apollo_inputs, functionality)
  return(P)
}

# ################################################################# #
#### MODEL ESTIMATION                                            ####
# ################################################################# #

model = apollo_estimate(apollo_beta, apollo_fixed, apollo_probabilities, apollo_inputs)

# ################################################################# #
#### MODEL OUTPUTS                                               ####
# ################################################################# #

# ----------------------------------------------------------------- #
#---- FORMATTED OUTPUT (TO SCREEN)                               ----
# ----------------------------------------------------------------- #

apollo_modelOutput(model)

# ----------------------------------------------------------------- #
#---- FORMATTED OUTPUT (TO FILE, using model name)               ----
# ----------------------------------------------------------------- #

apollo_saveOutput(model)


# ################################################################# #
##### POST-PROCESSING                                            ####
# ################################################################# #

### Print outputs of additional diagnostics to new output file (remember to close file writing when complete)
apollo_sink()

# ----------------------------------------------------------------- #
#---- MODEL PREDICTIONS                                          ----
# ----------------------------------------------------------------- #

model = apollo_loadModel(apollo_inputs$apollo_control$modelName)
apollo_inputs = apollo_validateInputs(database=dbVal)
apollo_inputs$apollo_control$nCores = 4
pred = apollo_prediction(model, apollo_probabilities, apollo_inputs)
XObs = cbind(work      =     dbVal$t_a02/60,
              school   =     dbVal$t_a03/60,
              shopping =     dbVal$t_a04/60,
              private  =     dbVal$t_a05/60,
              leisure  = dbVal$t_leisure/60)
XPre = pred[,4:8]

round(sqrt(colMeans((XObs - XPre)^2)),2) 
round(sqrt(mean((colSums(XObs) - colSums(XPre))^2)),2) 

# ----------------------------------------------------------------- #
#---- switch off writing to file                                 ----
# ----------------------------------------------------------------- #

apollo_sink()